package com.eqdd.yiqidian.ui.discover.makerspace

import android.app.Activity
import android.content.Intent
import android.support.v7.widget.GridLayoutManager
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.GridSpacingItemDecoration
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.BaseActivity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.rebuild.HttpResultRows
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource
import com.eqdd.yiqidian.http.*
import com.eqdd.yiqidian.kotlin.bottomDialog
import com.eqdd.yiqidian.kotlin.deleteDialog
import com.eqdd.yiqidian.kotlin.imgPathPreview
import com.eqdd.yiqidian.utils.ImageUtil
import com.eqdd.yiqidian.utils.PicUtil
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.lzy.okrx2.adapter.FlowableBody
import com.shizhefei.mvc.MVCCoolHelper
import io.reactivex.Flowable
import kotlinx.android.synthetic.main.activity_recyclerview_refresh.*
import kotlinx.android.synthetic.main.activity_title.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.toast
import java.io.File

/**
 * Created by jhj on 18-8-11.
 */
class MakerPhotoActivity : BaseActivity() {

    private var mvcHelper: MVCCoolHelper<List<PhotoBean>>? = null
    private var menuId: Int = -1
    private var isResult = false
    private var makerGuid: String? = null

    override fun initBinding() {
        setContentView(R.layout.activity_recyclerview_refresh)
        val title = intent.getStringExtra(Config.TITLE)
        initTopTitleBar(View.VISIBLE, title)
        back.onClick {
            if (isResult) {
                resultFinish()
            } else {
                finish()
            }
        }
    }


    override fun initData() {
        var pageNum = 0
        menuId = intent.getIntExtra(Config.ID, -1)
        makerGuid = intent.getStringExtra("makerGuid")
        val screenWidth = resources.displayMetrics.widthPixels
        val photoSize = (screenWidth - 40) / 3
        val params = LinearLayout.LayoutParams(photoSize, photoSize)
        val type = intent.getIntExtra(Config.TYPE, 0)
        if (menuId == -1 || makerGuid == null) {
            toast("获取详情失败")
            finish()
            return
        }
        val list = arrayListOf<PhotoBean>()
        MVCCoolHelper.setLoadViewFractory(CustomLoadViewFactory().setShowFooter(false))
        mvcHelper = MVCCoolHelper<List<PhotoBean>>(coolRefreshView)
        recyclerView.layoutManager = GridLayoutManager(this, 3)
        recyclerView.addItemDecoration(GridSpacingItemDecoration(3, 10, true))
        val slimAdapterEx = SlimAdapterEx.create()
                .register<PhotoBean>(R.layout.list_item_182, SlimInjector<PhotoBean> { data, injector ->
                    if (data?.isAdd == true) {
                        injector
                                ?.with<LinearLayout>(R.id.layout_add) {
                                    it.layoutParams = params
                                }
                                ?.text(R.id.tv_add, "新增图片")
                                ?.visible(R.id.layout_addg)
                                ?.gone(R.id.linearLayout)
                                ?.clicked(R.id.layout_add) {
                                    PicUtil.multi(this, null)
                                }

                    } else {
                        injector
                                ?.with<ImageView>(R.id.imageView) {
                                    it.layoutParams = params
                                    ImageUtil.setImage(data?.imageUrl, it)
                                }
                                ?.gone(R.id.tv_name)
                                ?.gone(R.id.tv_count)
                                ?.visible(R.id.linearLayout)
                                ?.gone(R.id.layout_addg)
                    }
                })
                .attachTo(recyclerView)
                .updateData(list as List<PhotoBean>?) as SlimAdapterEx<PhotoBean>?
        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener { recyclerView, position, v ->
                    val imageList = arrayListOf<String>()
                    slimAdapterEx?.data?.forEachIndexed { index, photoBean ->
                        photoBean.imageUrl?.let { imageList.add(it) }
                    }
                    if (type == 1) {
                        imgPathPreview(imageList, position)
                    } else {
                        imgPathPreview(imageList, position - 1)
                    }
                }
                .setOnItemLongClickListener { recyclerView, position, v ->
                    if (type == 0) {
                        bottomDialog(arrayListOf("设置为相册封面", "删除")) {
                            val data = slimAdapterEx?.getDataItem(position)
                            when (it) {
                                1 -> {

                                    OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.PHOTO_MENU_BG)
                                            .params("userGuid", makerGuid)
                                            .params("imageId", data?.Id ?: 0)
                                            .params("menuId", menuId)
                                            .execute(object : DialogCallBack<HttpResult<*>>(this@MakerPhotoActivity) {
                                                override fun onSuccess(response: Response<HttpResult<*>>) {
                                                    val httpResult = response.body()
                                                    if (httpResult.status == 200) {
                                                        isResult = true
                                                        toast(httpResult.msg)
                                                    } else {
                                                        toast(httpResult.msg ?: "设置失败")
                                                    }
                                                }
                                            })
                                }
                                2 -> {
                                    deleteDialog(HttpConfig.BASE_URL + HttpConfig.PHOTO_DELETE, "是否删除该图片？", "lecturePhotoId" to data?.Id, "menuId" to menuId,isFinish = false){
                                        isResult = true
                                        slimAdapterEx?.data?.removeAt(position)
                                        slimAdapterEx?.notifyItemRemoved(position)
                                    }


                                }
                            }
                        }
                    }
                    true
                }

        val dataSource = ModelRx2DataSource<PhotoBean>(ModelRx2DataSource.OnLoadSource<PhotoBean> { page, register ->
            if (page == 1) {
                pageNum = 0
            }
            OkGo.post<HttpResultRows<PhotoBean>>(HttpConfig.BASE_URL + HttpConfig.PHOTO_LIST)
                    .params("page", pageNum)
                    .params("menuId", menuId)
                    .converter(object : JsonConverter<HttpResultRows<PhotoBean>>() {
                        override fun test() {
                            super.test()
                        }
                    })
                    .adapt(FlowableBody<HttpResultRows<PhotoBean>>())
                    .flatMap { result ->
                        if (page == 1) {
                            mvcHelper?.isAutoLoadMore = true
                        }
                        pageNum = result.items.page

                        val dataList = result.items.rows ?: arrayListOf<PhotoBean>()

                        if (pageNum == 1 && type == 0) {
                            val bean = PhotoBean()
                            bean.isAdd = true
                            dataList.add(0, bean)
                        }

                        Flowable.just<MutableList<PhotoBean>>(
                                dataList as MutableList<PhotoBean>?
                                        ?: mutableListOf<PhotoBean>()
                        )

                    }

        }, 20)
        mvcHelper?.setDataSource(dataSource)
        mvcHelper?.adapter = slimAdapterEx
        mvcHelper?.refresh()
    }

    override fun setView() {
    }

    override fun onDestroy() {
        super.onDestroy()
        MVCCoolHelper.setLoadViewFractory(CustomLoadViewFactory().setShowFooter(true))
    }

    override fun onBackPressed() {
        if (isResult) {
            resultFinish()
        } else {
            super.onBackPressed()
        }

    }

    fun resultFinish() {
        setResult(Activity.RESULT_OK)
        finish()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {
            val localMedias = PictureSelector.obtainMultipleResult(data)
            val params = OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.PHOTO_ADD)
                    .params("userGuid", makerGuid)
                    .params("menuId", menuId)
            for (i in localMedias.indices) {
                params.params("file", File(localMedias[i].compressPath))
            }
            params.execute(object : DialogCallBack<HttpResult<*>>(this@MakerPhotoActivity) {
                override fun onSuccess(response: Response<HttpResult<*>>) {
                    val httpResult = response.body()
                    if (httpResult.status == 200) {
                        isResult = true
                        mvcHelper?.refresh()
                    }
                }
            })
        }

    }

    class PhotoBean {
        var Id: Int = 0
        var lectureId: String? = null
        var creater: String? = null
        var createTime: String? = null
        var imageUrl: String? = null
        var imageName: String? = null
        var menuId: Int = 0
        var isAdd = false
    }

}